<template>
  <div class="users-management">
    <div class="page-header">
      <h2 class="page-title">用户管理</h2>
      <div class="page-actions">
        <!-- <button class="btn primary" @click="showAddModal = true">
          <PlusIcon size="16" />
          添加用户
        </button> -->
        <div class="search-box">
          <input type="text" placeholder="搜索用户名或邮箱..." v-model="searchQuery" @input="handleSearch">
          <SearchIcon size="16" />
        </div>
      </div>
    </div>

    <div class="filters">
      <div class="filter-group">
        <label>用户角色:</label>
        <select v-model="selectedRole" @change="filterUsers">
          <option value="">全部</option>
          <option v-for="role in roles" :value="role.value" :key="role.value">
            {{ role.label }}
          </option>
        </select>
      </div>

      <div class="filter-group">
        <label>注册时间:</label>
        <select v-model="selectedTimeRange" @change="filterUsers">
          <option value="">全部</option>
          <option value="today">今天</option>
          <option value="week">本周</option>
          <option value="month">本月</option>
        </select>
      </div>

      <div class="filter-group">
        <label>状态:</label>
        <select v-model="selectedStatus" @change="filterUsers">
          <option value="">全部</option>
          <option value="active">正常</option>
          <option value="inactive">未知</option>
          <option value="banned">已封禁</option>
        </select>
      </div>
    </div>

    <div class="users-table">
      <table>
        <thead>
          <tr>
            <th>用户</th>
            <th>邮箱</th>
            <th>角色</th>
            <th>学习数据</th>
            <th>注册时间</th>
            <th>状态</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="user in paginatedUsers" :key="user.id">
            <td>
              <div class="user-cell">
                <img :src="user.avatar" :alt="user.name" class="user-avatar">
                <div>
                  <strong>{{ user.name }}</strong>
                  <span class="user-id">ID: {{ user.id }}</span>
                </div>
              </div>
            </td>
            <td>{{ user.email }}</td>
            <td>
              <span class="role-badge" :class="user.role">
                {{ getRoleLabel(user.role) }}
              </span>
            </td>
            <td>
              <div class="stats-cell">
                <span title="学习天数">{{ user.stats.days }} 天</span>
                <span title="掌握单词">{{ user.stats.words }} 词</span>
              </div>
            </td>
            <td>{{ formatDate(user.createdAt) }}</td>
            <td>
              <span class="status-badge" :class="user.status">
                {{ getStatusLabel(user.status) }}
              </span>
            </td>
            <td>
              <!-- <button class="btn-icon" @click="editUser(user)" title="编辑">
                <EditIcon size="16" />
              </button> -->
              <button class="btn-icon"
                :class="{ 'danger': user.status !== 'banned', 'success': user.status === 'banned' }"
                @click="toggleBanUser(user)" :title="user.status === 'banned' ? '解封用户' : '封禁用户'"
                v-if="user.role !== 'super_admin' && user.role !== 'admin'">
                <BanIcon size="16" v-if="user.status !== 'banned'" />
                <UnlockIcon size="16" v-else />
              </button>
              <button class="btn-icon danger" @click="confirmDelete(user.id)" title="删除"
                v-if="user.role !== 'super_admin' && user.role !== 'admin'">
                <TrashIcon size="16" />
              </button>
            </td>
          </tr>
        </tbody>
      </table>

      <div class="pagination" v-if="filteredUsers.length > itemsPerPage">
        <button @click="currentPage--" :disabled="currentPage === 1" class="pagination-btn">
          上一页
        </button>
        <span class="page-info">第 {{ currentPage }} 页 / 共 {{ totalPages }} 页</span>
        <button @click="currentPage++" :disabled="currentPage === totalPages" class="pagination-btn">
          下一页
        </button>
      </div>
    </div>

    <!-- 添加/编辑用户模态框 -->
    <UserModal v-if="showAddModal || showEditModal" :user="currentUser" :roles="roles" @save="handleSaveUser"
      @close="closeModal" />

    <!-- 删除确认模态框 -->
    <ConfirmModal v-if="showDeleteModal" title="确认删除" :message="`确定要删除用户 ${userToDeleteName} 吗？此操作无法撤销。`"
      @confirm="deleteUser" @cancel="showDeleteModal = false" />
  </div>
</template>

<script setup>
import { ref, computed, onMounted, reactive } from 'vue'
import { PlusIcon, SearchIcon, EditIcon, TrashIcon, BanIcon, UnlockIcon } from 'lucide-vue-next'
import UserModal from '../../components/UserModal.vue'
import { ElMessage } from 'element-plus'


import ConfirmModal from '../../components/ConfirmModal.vue'


import { getUsersArr, deleteAdminUser, deleteRegularUsers, updateUserStatus } from '../../api/authService.js'
const userId = localStorage.getItem("userId");
// 模拟用户数据
const users = ref([])

const roles = ref([
  { value: 'admin', label: '管理员' },
  { value: 'super_admin', label: '超级管理员' },
  { value: 'user', label: '普通用户' }
])

// 搜索和筛选
const searchQuery = ref('')
const selectedRole = ref('')
const selectedTimeRange = ref('')
const selectedStatus = ref('')



const filteredUsers = computed(() => {
  let result = [...users.value]

  // 搜索过滤
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    result = result.filter(user =>
      user.name.toLowerCase().includes(query) ||
      user.email.toLowerCase().includes(query)
    )
  }

  // 角色过滤
  if (selectedRole.value) {
    // console.log(selectedRole.value);
    // console.log(result);
    result = result.filter(user => user.role === selectedRole.value)
  }

  // 状态过滤
  if (selectedStatus.value) {
    result = result.filter(user => user.status === selectedStatus.value)
  }

  // 时间范围过滤
  if (selectedTimeRange.value) {
    const now = new Date()
    let startDate

    switch (selectedTimeRange.value) {
      case 'today':
        startDate = new Date(now.setHours(0, 0, 0, 0))
        break
      case 'week':
        startDate = new Date(now.setDate(now.getDate() - now.getDay()))
        break
      case 'month':
        startDate = new Date(now.getFullYear(), now.getMonth(), 1)
        break
    }

    result = result.filter(user => {
      const userDate = new Date(user.createdAt)
      return userDate >= startDate
    })
  }

  // 按注册时间排序
  result.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt))

  return result
})

// 分页
const currentPage = ref(1)
const itemsPerPage = 5

const totalPages = computed(() => Math.ceil(filteredUsers.value.length / itemsPerPage))

const paginatedUsers = computed(() => {
  const start = (currentPage.value - 1) * itemsPerPage
  const end = start + itemsPerPage
  return filteredUsers.value.slice(start, end)
})

// 模态框状态
const showAddModal = ref(false)
const showEditModal = ref(false)
const showDeleteModal = ref(false)
const currentUser = ref(null)
const userToDelete = ref(null)
const userToDeleteName = computed(() => {
  const user = users.value.find(u => u.id === userToDelete.value)
  return user ? user.name : ''
})

// 辅助函数
const getRoleLabel = (role) => {
  // console.log(role, 'role');
  const roleObj = roles.value.find(r => r.value === role)
  return roleObj ? roleObj.label : '未知'
}

const getStatusLabel = (status) => {
  const statusMap = {
    active: '正常',
    inactive: '未知',
    banned: '已封禁'
  }
  return statusMap[status] || '未知'
}

const formatDate = (dateString) => {
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN')
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
}

// 过滤处理
const filterUsers = () => {
  currentPage.value = 1
}

// 用户操作
const editUser = (user) => {
  currentUser.value = { ...user }
  showEditModal.value = true
}

const toggleBanUser = (user) => {
  console.log(user.beforeId.id, 'toggleBanUser');
  // handleToggleStatus()
  const index = users.value.findIndex(u => u.id === user.id)
  console.log(user.status, 'user.status');
  var statusFlag = 1;
  if (user.status === 'banned') {
    statusFlag = 0;
  } else {
    statusFlag = 1;
  }
  handleToggleStatus(user.beforeId.id, statusFlag)
  if (index !== -1) {
    users.value[index].status = user.status === 'banned' ? 'active' : 'banned'
  }
}

const handleToggleStatus = async (userId, currentStatus) => {
  const newStatus = currentStatus === 1 ? 0 : 1;

  const res = await updateUserStatus(userId, newStatus);

  if (res.success) {
    alert(res.message);
    // 可以刷新用户列表或者更新 UI
  } else {
    alert(res.message);
  }
};

const confirmDelete = (id) => {
  userToDelete.value = id
  showDeleteModal.value = true
  // console.log(userToDelete.value);

}
// 确定删除键 用户
const deleteUser = () => {
  // console.log(userToDelete.value, '删除用户');
  const indexUser = users.value[users.value.findIndex(user => user.id === userToDelete.value)]
  // console.log(indexUser.beforeId.role);
  if (indexUser.beforeId.role === 'user') {
    deleteUserData(indexUser.beforeId.id)
    console.log('用户');
  } else {
    deleteAdminUserData(indexUser.beforeId.id)
    console.log('管理员');
  }
  users.value = users.value.filter(user => user.id !== userToDelete.value)
  // console.log(users.value);
  showDeleteModal.value = false
  userToDelete.value = null
}


const deleteAdminUserData = async (id) => {
  try {
    const res = await deleteAdminUser(id);
    // console.log(res, '获取用户数据');
    if (res) {

      console.log(res, '删除管理员成功');
    } else {
      ElMessage.error(res.message || "删除管理员失败");
    }
  } catch (error) {
    ElMessage.error("获取失败: ");
  } finally {
    // loading.value = false;
  }
};
const deleteUserData = async (id) => {
  try {
    const res = await deleteRegularUsers(id);
    // console.log(res, '获取用户数据');
    if (res) {

      console.log(res, '删除管理员成功');
    } else {
      ElMessage.error(res.message || "删除管理员失败");
    }
  } catch (error) {
    ElMessage.error("获取失败: ");
  } finally {
    // loading.value = false;
  }
};
const handleSaveUser = (userData) => {
  if (userData.id) {
    // 更新现有用户
    const index = users.value.findIndex(u => u.id === userData.id)
    if (index !== -1) {
      users.value[index] = userData
    }
  } else {
    // 添加新用户
    const newUser = {
      ...userData,
      id: Math.max(...users.value.map(u => u.id)) + 1,
      createdAt: new Date().toISOString(),
      status: 'active',
      stats: { days: 0, words: 0 }
    }
    users.value.unshift(newUser)
  }

  closeModal()
}

const closeModal = () => {
  showAddModal.value = false
  showEditModal.value = false
  currentUser.value = null
}
const loadGetUserData = async () => {
  try {
    const res = await getUsersArr(userId);
    // console.log(res, '获取用户数据');
    if (res) {
      handNewUserData(res)
      // console.log(res, '获取用户数据');
    } else {
      ElMessage.error(res.message || "获取用户列表失败");
    }
  } catch (error) {
    ElMessage.error("获取失败: ");
  } finally {
    // loading.value = false;
  }
};

const handNewUserData = (objUser) => {
  var usersFlag = []
  let idCounter = 1;  // 初始 ID，从 1 开始累加
  console.log(objUser, 'objUser');
  if (objUser.users && objUser.admin_users) {
    const { users, admin_users } = objUser;

    // 转换 users 数据
    const transformedUsers = users.map(user => {
      return {
        beforeId: {
          id: user.id,
          role: 'user'
        },
        id: idCounter++,  // 使用 idCounter 赋值，并自增
        name: user.username,
        email: user.email || '暂无',
        avatar: '../../../public/avatar/' + user.avatar + '.png',
        role: 'user',
        status: user.status === 1 ? 'active' : 'banned',
        createdAt: formatDateflag(user.created_at),  // 格式化时间为中国时间
        stats: {
          days: 120,
          words: 3621
        }
      };
    });

    // 转换 admin_users 数据
    const transformedAdminUsers = admin_users.map(user => {
      return {
        beforeId: {
          id: user.id,
          role: user.role
        },
        id: idCounter++,  // 使用 idCounter 赋值，并自增
        name: user.username,
        email: user.email || '暂无',
        avatar: '../../../public/avatar/' + user.avatar + '.png',
        role: user.role,
        status: 'inactive',
        createdAt: formatDateflag(user.created_at),  // 格式化时间为中国时间
        stats: {
          days: '--',
          words: '--'
        }
      };
    });

    usersFlag = [...transformedUsers, ...transformedAdminUsers];
  } else {
    const { users } = objUser;

    // 转换 users 数据
    const transformedUsers = users.map(user => {
      return {
        beforeId: {
          id: user.id,
          role: 'user'
        },
        id: idCounter++,  // 使用 idCounter 赋值，并自增
        name: user.username,
        email: user.email || '暂无',
        avatar: '../../../public/avatar/' + user.avatar + '.png',
        role: 'user',
        status: user.status === 1 ? 'active' : 'banned',
        createdAt: formatDateflag(user.created_at),  // 格式化时间为中国时间
        stats: {
          days: 120,
          words: 3621
        }
      };
    });

    usersFlag = [...transformedUsers];
  }

  users.value = usersFlag;
  // console.log(users.value);
};

// 时间格式化函数，转换为中国时间
const formatDateflag = (isoDate) => {
  const date = new Date(isoDate);  // 将 ISO 日期字符串转换为 Date 对象
  const options = {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: false,  // 24小时制
    timeZone: 'Asia/Shanghai',  // 设置时区为中国时间
  };
  return date.toLocaleString('zh-CN', options);  // 格式化为中国本地时间（北京时间）
};


onMounted(() => {
  loadGetUserData()
})
</script>

<style scoped>
.users-management {
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 1rem;
}

.page-title {
  margin: 0;
  font-size: 1.5rem;
}

.page-actions {
  display: flex;
  gap: 1rem;
  align-items: center;
}

.btn {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.5rem 1rem;
  border-radius: 4px;
  border: none;
  cursor: pointer;
  font-weight: 500;
  transition: all 0.2s ease;
}

.btn.primary {
  background-color: var(--primary-color);
  color: white;
}

.btn.primary:hover {
  background-color: var(--primary-color);
  opacity: 0.9;
}

.search-box {
  position: relative;
  display: flex;
  align-items: center;
}

.search-box input {
  padding: 0.5rem 1rem 0.5rem 2rem;
  border: 1px solid var(--border-color);
  border-radius: 4px;
  background-color: var(--card-bg);
  color: var(--text-color);
  width: 200px;
}

.search-box svg {
  position: absolute;
  left: 0.7rem;
  color: var(--text-secondary);
}

.filters {
  display: flex;
  gap: 1.5rem;
  flex-wrap: wrap;
}

.filter-group {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.filter-group label {
  font-size: 0.9rem;
  color: var(--text-secondary);
}

.filter-group select {
  padding: 0.3rem 0.5rem;
  border: 1px solid var(--border-color);
  border-radius: 4px;
  background-color: var(--card-bg);
  color: var(--text-color);
}

.users-table {
  overflow-x: auto;
}

table {
  width: 100%;
  border-collapse: collapse;
  background-color: var(--card-bg);
  box-shadow: var(--shadow);
  border-radius: 8px;
  overflow: hidden;
}

th,
td {
  padding: 1rem;
  text-align: left;
  border-bottom: 1px solid var(--border-color);
}

th {
  background-color: var(--hover-bg);
  font-weight: 600;
}

.user-cell {
  display: flex;
  align-items: center;
  gap: 0.8rem;
}

.user-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
}

.user-id {
  display: block;
  font-size: 0.8rem;
  color: var(--text-secondary);
  margin-top: 0.3rem;
}

.role-badge {
  display: inline-block;
  padding: 0.2rem 0.6rem;
  border-radius: 12px;
  font-size: 0.8rem;
  background-color: var(--hover-bg);
}

.role-badge.admin {
  background-color: rgba(220, 53, 69, 0.1);
  color: var(--danger-color);
}

.role-badge.super_admin {
  background-color: rgba(255, 193, 7, 0.1);
  color: var(--warning-color);
}

.role-badge.user {
  background-color: rgba(108, 117, 125, 0.1);
  color: var(--secondary-color);
}

.stats-cell {
  display: flex;
  flex-direction: column;
  gap: 0.3rem;
}

.stats-cell span {
  font-size: 0.9rem;
}

.status-badge {
  display: inline-block;
  padding: 0.2rem 0.6rem;
  border-radius: 12px;
  font-size: 0.8rem;
}

.status-badge.active {
  background-color: rgba(40, 167, 69, 0.1);
  color: var(--success-color);
}

.status-badge.inactive {
  background-color: rgba(108, 117, 125, 0.1);
  color: var(--secondary-color);
}

.status-badge.banned {
  background-color: rgba(220, 53, 69, 0.1);
  color: var(--danger-color);
}

.btn-icon {
  background: none;
  border: none;
  cursor: pointer;
  padding: 0.3rem;
  border-radius: 4px;
  color: var(--text-secondary);
  margin-right: 0.5rem;
}

.btn-icon:hover {
  background-color: var(--hover-bg);
}

.btn-icon.danger:hover {
  color: var(--danger-color);
}

.btn-icon.success:hover {
  color: var(--success-color);
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 1rem;
  margin-top: 1.5rem;
}

.pagination-btn {
  padding: 0.5rem 1rem;
  border: 1px solid var(--border-color);
  background-color: var(--card-bg);
  color: var(--text-color);
  border-radius: 4px;
  cursor: pointer;
}

.pagination-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.page-info {
  font-size: 0.9rem;
  color: var(--text-secondary);
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
  }

  .page-actions {
    width: 100%;
    justify-content: space-between;
  }

  .search-box input {
    width: 100%;
  }

  .filters {
    gap: 1rem;
  }

  table {
    display: block;
    overflow-x: auto;
    white-space: nowrap;
  }
}
</style>